<template>
  <div class="app-container" v-loading="loading" style="overflow-x: hidden">
    <div class="headerINfo">
      <h4 style="margin-top: 0px">涂膜一工序日常巡检表</h4>
      <h5>{{ mainData.taskName }}</h5>
    </div>
    <div class="mainInfo">
      <div class="leftInfo">
        <div class="infoLi" :key="index" v-for="(i, index) in baseInfo">
          <p>{{ i.taskName }}</p>
          <span
            style="cursor: pointer"
            v-for="(item, itemIndex) in i.taskRecordList"
            @click="chioseClick(item, index + '-' + itemIndex)"
            :key="itemIndex + 'Ch'"
            :class="active == index + '-' + itemIndex ? 'activeClass' : ''"
          >
            {{ item.taskTimeStart.split(" ")[1] + " - " + item.taskTimeEnd.split(" ")[1] }}
          </span>
        </div>
      </div>
      <div class="rightInfo">
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="工段" prop="workshopName">
              {{ mainData.workshopName }}
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="产线" prop="productLineName">
              {{ mainData.productLineName }}
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="工艺段" prop="sectionName">
              {{ mainData.sectionName }}
            </el-form-item>
          </el-col>

          <el-col :span="6">
            <el-form-item label="班次" prop="classesName">
              {{ mainData.classesName }}
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="班组" prop="workGroupName">
              {{ mainData.workGroupName }}
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="生产日期" prop="prodDate">
              {{ mainData.prodDate }}
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="订单" prop="prodName">
              {{ mainData.prodName }}
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="执行人" prop="userNames">
              {{ mainData.userNames }}
            </el-form-item>
          </el-col>
        </el-row>
        <div>
          <!--  @submit="onSubmit" -->
          <form-create
            v-if="showCreat"
            :disabled="formCreateDisabled"
            :rule="rule"
            :option="options"
            v-model:api="fApi"
            v-model="formData"
          ></form-create>
          <!-- v-model="aa"  绑定的数据  可以回填 -->
        </div>
      </div>
    </div>
  </div>
</template>

<script setup name="changeShifts">
import { getExecuteList, storeTask, submitTask } from "@/api/productionMgt/taskCenter";
import { ref } from "vue";
import { useAttrs, getCurrentInstance, toRefs, watch, onMounted } from "vue";
const attrs = useAttrs();
const { proxy } = getCurrentInstance();
const loading = ref(false);
const fApi = ref(null);
const rule = ref();
const options = ref();
const active = ref();
const listData = ref();
const emit = defineEmits(["close", "setTitle", "setActions", "setIsActionTop"]);
const actions = ref();
const baseInfo = ref();
const mainData = ref({});
const showDisabled = ref(false);
const formCreateDisabled = ref(false);
const formData = ref({});
const showCreat = ref(false);
watch(
  () => active.value,
  (newValue) => {
    if (newValue) {
      console.log(newValue);
      showCreat.value = false;
      let index1 = newValue.split("-")[0];
      let index2 = newValue.split("-")[1];
      // 获取当前 时间段任务详情
      mainData.value = baseInfo.value[index1].taskRecordList[index2];
      if (mainData.value.content) {
        const obj = JSON.parse(mainData.value.content);
        // eslint-disable-next-line no-undef
        rule.value = formCreate.parseJson(obj.rule);
        // eslint-disable-next-line no-undef
        options.value = formCreate.parseJson(obj.options);
        formData.value = mainData.value.taskDetailContent;
      }
      if (mainData.value.taskDetailContent) {
        formData.value = mainData.value.taskDetailContent;
      }

      setTimeout(() => {
        showCreat.value = true;
      }, 300);
    }
  }
);
function chioseClick(info, index) {
  active.value = index;
  setAction(info);
}

function getDetail(id) {
  loading.value = true;
  getExecuteList(id).then((res) => {
    loading.value = false;
    baseInfo.value = res.data;

    baseInfo.value.forEach((item, index) => {
      if (item.taskRecordList && item.taskRecordList.length) {
        item.taskRecordList.forEach((info, infoIndex) => {
          if (listData.value.taskRecordDetailId == info.taskRecordDetailId) {
            // 根据id  找到 那一条时间段是应该显示的
            active.value = index + "-" + infoIndex;
            setAction(info);
            // timeDetail(info.taskRecordDetailId)
          }
        });
      }
    });
    if (!active.value) {
      active.value = "0-0";
      actions.value = [
        {
          text: "取 消",
          theme: "",
          handle: () => {
            cancel();
          },
        },
      ];
      emit("setActions", actions.value);
      formCreateDisabled.value = true;
    }
  });
}
// // 获取某个时间段下的 详情  表单配置
// function timeDetail(id){
//   getExecuteList(id).then((res)=>{
//     console.log(res);
//   })
// }
// 设置按钮 权限
function setAction(info) {
  // const timeString = new Date().toLocaleTimeString(); // 或者使用 now.toTimeString() 根据需要

  const timeString = new Date().getTime();

  // console.log(timeString);
  // const timeStart = info.taskTimeStart.split(" ")[1];
  const timeStart = new Date(info.taskTimeStart).getTime();
  // const timeEnd = info.taskTimeEnd.split(" ")[1];
  // 仅当前时间≥任务开始时间时，提供填报的“提交、暂存、取消”按钮。
  // 暂存、提交操作仅针对当前时段任务。
  // 当前时间＜任务开始时间时，不提供填报的“提交、暂存”按钮。
  // 已填报完成的任务，不提供填报的“提交、暂存”按钮。已填报完成的任务，不提供填报的“提交、暂存”按钮。
  //  || timeToMilliseconds(timeString) > timeToMilliseconds(timeEnd)
  if (timeString < timeStart || info.status == "3" || showDisabled.value) {
    // 未到开始时间  只有取消按钮 //  状态是已提交（已完成）的 只有取消按钮
    actions.value = [
      {
        text: "取 消",
        theme: "",
        handle: () => {
          cancel();
        },
      },
    ];
    emit("setActions", actions.value);
    formCreateDisabled.value = true;
  } else {
    actions.value = [
      {
        text: "取 消",
        theme: "",
        handle: () => {
          cancel();
        },
      },
      {
        text: "暂 存",
        theme: "",
        handle: () => {
          save();
        },
      },
      {
        text: "提 交",
        theme: "primary",
        handle: () => {
          submit();
        },
        loading: false,
      },
    ];
    emit("setActions", actions.value);
    formCreateDisabled.value = false;
  }
}
// 将时分秒 转换成毫秒
function timeToMilliseconds(timeStr) {
  const [hours, minutes, seconds] = timeStr.split(":").map(Number);
  return (hours * 3600 + minutes * 60 + seconds) * 1000; // 转换为毫秒
}
// 暂存
function save() {
  fApi.value
    .submit()
    .then((formData) => {
      // 推荐
      console.log("表单数据:", formData);
      console.log("当前表单配置:", rule.value);
      console.log("当前时间段数据:", mainData.value);
      // if (mainData.value.content) {
      //   const obj = JSON.parse(mainData.value.content);
      //   // eslint-disable-next-line no-undef
      //   obj.rule = formCreate.toJson(rule.value);
      //   mainData.value.content = JSON.stringify(obj);
      // }
      mainData.value.taskDetailContent = formData;
      storeTask(mainData.value).then((result) => {
        console.log(result);
        proxy.$modal.msgSuccess("暂存成功");
      });
      // 提交后的逻辑处理
    })
    .catch((formData) => {
      console.log("表单提交失败:", formData);
    });
}
// 提交
function submit() {
  fApi.value
    .submit()
    .then((formData) => {
      // 推荐
      console.log("表单数据:", formData);
      console.log("当前表单配置:", rule.value);
      console.log("当前时间段数据:", mainData.value);

      mainData.value.taskDetailContent = formData;
      submitTask(mainData.value).then((result) => {
        console.log(result);
        mainData.value.status = '3'
        setAction(mainData.value)
        proxy.$modal.msgSuccess("提交成功");
      });
      // 提交后的逻辑处理
    })
    .catch((formData) => {
      console.log("表单提交失败:", formData);
    });
}
function cancel() {
  emit("close");
}
// function onSubmit(data) {
//   console.log(data);
//   console.log(rule.value);
// }
onMounted(async () => {
  const { data } = attrs;
  listData.value = data;
  // 从别的页面打开这里 会传这个字段  传了 就不允许编辑
  showDisabled.value = data.showDisabled;
  if (data && data.showDisabled) {
    formCreateDisabled.value = true;
  }
  if (data?.id) {
    getDetail(data.id || data.taskRecordId);
  }
});
</script>
<style lang="scss" scoped>
.headerINfo {
  width: 100%;
  text-align: center;
}
.mainInfo {
  width: 100%;
  display: flex;
  justify-content: flex-start;
  .leftInfo {
    width: 200px;
    border-right: 1px solid #f0f0f0;
    min-height: 300px;
    max-height: calc(100vh - 315px);
    overflow-y: auto;
    .infoLi {
      width: 100%;
      margin-bottom: 15px;
      p {
        width: 100%;
        margin: 5px auto;
      }
      span {
        display: inline-block;
        margin: 10px 15px;
        font-size: 14px;
      }
    }
  }
  .rightInfo {
    flex: 1;
    min-height: 300px;
    padding-left: 20px;
    max-height: calc(100vh - 315px);
    overflow-y: auto;
    overflow-x: hidden;
  }
}
.activeClass {
  color: #0044a0;
}
</style>
